package listenTogether;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

@WebServlet("/listenTogether.UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求的字符编码为 UTF-8，防止文件名乱码
        request.setCharacterEncoding("UTF-8");

        // 获取项目的 music 文件夹路径
        String musicDirPath = getServletContext().getRealPath("/Music");
        File musicDir = new File(musicDirPath);
        if (!musicDir.exists()) {
            musicDir.mkdirs(); // 创建文件夹
        }

        // 获取上传的文件
        Part filePart = request.getPart("file");
        String fileName = filePart.getSubmittedFileName();

        // 检查文件扩展名是否是 .mp3
        if (fileName != null && fileName.endsWith(".mp3")) {
            // 将文件保存到 music 文件夹
            filePart.write(new File(musicDir, fileName).getAbsolutePath());
            response.getWriter().println("文件上传成功！");
        } else {
            response.getWriter().println("请上传 MP3 文件！");
        }

        // 重定向到播放器页面（根据实际项目路径调整路径）
        response.sendRedirect("player.jsp");
    }
}
